message = {
    currentlySendingMessage: false,
    newMsg: function() {
        $("body").on("click", "#userList", function() {
            $(".msgBoxTo").focus(); // set focus
        });
        $("body").on("click", ".newMsg", function() {
            var dataTagID = $(this).attr("dataTagID");
            var dataTitle = $(this).attr("dataTitle");
            var dataMessage = $(this).attr("dataMessage");

            var title = $("#" + dataTitle).val(); // msg title
            var msg = $("#" + dataMessage).val(); // msg text
            var msg = msg_nl2br(msg.replace(/\n/g, '<br>'));
            var userListID = $("#" + dataTagID).attr("data-tag-id"); // user recipient

            $(".newMsg").attr("disabled", "disabled");

            // File attachment
            var file_name = $(this).attr("data-file");
            var files = $(this).attr("data-get-file");
            var folder_location = $(this).attr("data-location");
            var imageLength = $("." + files).length;
            var img = {};
            $("." + files).each(function(eqindex) {
                img['name_' + eqindex] = $(this).attr("data-name");
            });

            action = "newMsg";

            if (userListID == "0") {
                showNotification({
                    message: "Please choose atleast one user.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
                $(".msgBoxTo").focus(); // set focus
                $(".newMsg").removeAttr("disabled");
            } else {
                if (title == "") {
                    showNotification({
                        message: "Please type your prefered title on your message.",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    $("#" + dataTitle).focus();
                    $(".newMsg").removeAttr("disabled");
                } else {
                    if (msg == "" && imageLength == 0) {
                        showNotification({
                            message: "Please include either message / attachment file.",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                        $(".newMsg").removeAttr("disabled");
                    } else {
                        var json_encode = JSON.stringify(img);

                        $.ajax({
                            type: "POST",
                            url: "/ajax/message",
                            data: {action: action, title: title, msg: msg, userListID: userListID, imagesGet: json_encode, folder_location: folder_location},
                            success: function(results) {
                                showNotification({
                                    message: "Message successfully sent.",
                                    type: "success",
                                    autoClose: true,
                                    duration: 3
                                });

                                var selectedConversationDivId = $('.active_vMsg').attr('id');
                                //Message.loadNewMessage(); // Load New Message
                                $(".loadMsgList").html(null); // remove inbox content
                                $("div.recipient").remove();
                                $(".crt_new_msg").hide();
                                $(".msg_container").show();
                                $("#" + dataTitle).val(null); // msg title
                                $("#" + dataMessage).val(null); // msg text
                                $("#" + dataTagID).attr("data-tag-id", "0");
                                get_loadMsg("load", "loadMsg", "", "", function() {
                                    //  reassign the selected conversation
                                    if (typeof selectedConversationDivId !== 'undefined') {
                                        $('#' + selectedConversationDivId).addClass('active_vMsg');
                                    }
                                }); // Load Msg
                                $("#popup_container, #popup_overlay").remove();

                                // Remove images uploaded on the preview
                                $(".previewImagePostUpload_1").html(null);
                                $(".imagePreviewUpload_1").hide();
                                $(".newMsg").removeAttr("disabled");

                                console.log(results);
                                $.event.trigger({
                                    type: 'newMessageSent',
                                    messageData: {
                                        id: results.newMessageId,
                                        msg: msg,
                                        message: msg, //  added for chat
                                        action: 'newMsg',
                                        imagesGet: json_encode,
                                        folder_location: folder_location,
                                        userListID: userListID
                                    }
                                });

                            }
                        });
                    }
                }
            }
        });
        // View Message Settings
        $("body").on("click", ".view_msg_settings", function() {
            var action = $(this).attr("data-action");
            $("ul." + action).show();
            $(this).addClass("open");
        });
        $("body").on("click", ".open, body", function() {
            var action = $(this).attr("data-action");
            $("ul." + action).hide();
            $(".open").removeClass("open");
        });

        // open and create message
        $("body").on("click", "._create_msg", function() {
            $(".crt_new_msg").show();
            $(".crt_new_msg").removeClass("display");
            $(".msg_container").hide();
            $("ul.dropdown-menu").hide();
            $(".open").removeClass("open");
            // Additional
            $(".loadMsgList li.active_vMsg").removeClass("active_vMsg");
            $(".white").removeClass("white");
            $(".deleteConversation").attr("data-id", "");
            $(".addPeopleConversation").attr("data-id", "");
            $(".addPeopleConversation").attr("data-re", "");
            $(".addPeopleConversation").attr("data-name", "");

            $(".conversationTo").html(null);
            $(".messagesOne").html(null);

        });
    },
    loadMsg: function() {
        $(".load_m").show();
        setTimeout(function() {
            get_loadMsg("load", "loadMsg", "", "");
        });
    },
    loadNewMsg: function() {
        $("body").on("click", ".inboxCount", function() {
            $(".loadMsgList").html(null);
            $(".more").remove();
            $(".load_m").show();
            setTimeout(function() {
                get_loadMsg("load", "loadMsg", "", "");
            });
        });
    },
    cNewMsg: function() {
        $("body").on("click", ".cNewMsg", function() {
            var messageDesign = '<h3><i class="icon-envelope"></i> Create your message here.</h3><div class="hr"></div><div class="crt_new_msg " style="float: left;width:100%;">' +
                    '<div style="overflow:auto;height:450px;padding: 5px;">' +
                    '<div id="userList" style="float: left;border: 1px solid #ddd;min-height: 40px;margin-top: 5px;width: 100%;padding-bottom: 8px;">' +
                    '<div style="float:left;margin-top: 13px;margin-left:12px;font-weight: bold;">' +
                    'To:' +
                    '</div>' +
                    '<input type="text" id="listRecipient2" class="input-small msgBoxTo" data-tag-id="0" style="border: none;box-shadow:none;margin-left: 12px;margin-top: 8px;">' +
                    '</div>' +
                    '<div style="float: left;width: 100%;"><div id="displayUser2"></div></div>' +
                    '<div id="msgTitle" style="float: left;border: 1px solid #ddd;min-height: 40px;margin-top: 5px;width: 100%;">' +
                    '<div style="float:left;margin-top: 13px;margin-left:12px;font-weight: bold;">' +
                    'Title:' +
                    '</div>' +
                    '<input type="text" id="title1" class="input-small" style="border: none;box-shadow:none;margin-left: 2px;margin-top: 8px;">' +
                    '</div>' +
                    //'<div id="msgBox1" contenteditable="true" style="float: left;border: 1px solid #ddd; min-height: 260px;margin-top: 5px;width: 100%;">'+
                    //
                    //'</div>'+
                    '<textarea id="msgBox1" style="float: left;border: 1px solid #ddd; min-height: 260px;margin-top: 5px;width: 100%;"></textarea>' +
                    '<center><button class="btn-basicBtn padding_5 cursor tip" data-original-title="Add Files" style="margin-top: 3px;">' +
                    '<form id="postFile_0" method="post" enctype="multipart/form-data" action="/ajax/uploadFile">' +
                    '<div class="postActions" style="margin-left: 5px;margin-top: 5px;">' +
                    '<div id="uniform-fileInput" class="uploader">' +
                    '<input type="file" data-action-id="0" value="upload"' +
                    'name="postFile" id="uploadForm_0" size="24" data-get-file="imagePost_0" data-show="imagePreviewUpload_0" data-form="postFile_0" data-location="previewImagePostUpload_0" data-action-type="postFile" style="opacity: 0;" class="postFile">' +
                    '<span id="uploadFilename_0" class="filename">No file selected</span>' +
                    '<span class="action">Choose File</span>' +
                    '<input type="hidden" value="messageFileUpload" name="uploadType">' +
                    '<input type="hidden" value="messageUpload" name="uploadFolder">' +
                    '</div>' +
                    '<img src="/images/loader/loader.gif" class="postFileLoad pull-left display" style="margin-left: 5px;margin-top:6px;"/>' +
                    '</div>' +
                    '</form>' +
                    '</button>' +
                    '<div class="imagePreviewUpload_0 display" style="float: left;width: 100%;border: 1px solid #D5D5D5;margin-top:10px;background-color: #fff;margin-bottom: 5px;"> ' +
                    '<div style="padding: 5px;" class="previewImagePostUpload_0">' +
                    '</div>' +
                    '</div></center><br>' +
                    '<input type="button" class="btn-basicBtn pull-right" id="popup_cancel" value="Cancel"  style="margin-top:10px;">' +
                    '<input type="button" class="btn-blueBtn pull-right newMsg" dataTitle="title1" dataMessage="msgBox1" dataTagID="listRecipient2" value="SEND" data-get-file="imagePost_0" data-location="messageUpload" data-file="imagePreviewUpload_0" style="margin-top:10px;margin-right:5px;">' +
                    '</div>' +
                    '</div>';
            //$("body").html(messageDesign);
            jDialog(messageDesign, '', '', '', '50', function() {
            });
            $("#listRecipient2").autoComplete({
                table_search: "tbuser",
                search_type: "users",
                event: "#listRecipient2",
                display: "#displayUser2",
                allow_select: true,
                allow_delete: true
            });
        });
    },
    viewMsg: function(elements) {
        $("body").on("click", elements, function() {
            $('.scrollbarP').perfectScrollbar('destroy');
            var ret = "";
            var id = $(this).attr("data-id");

            $("#loading_" + id).show();
            $("#msg_" + id).removeClass("gray_bg");
            $(".active_vMsg").removeClass("active_vMsg");
            $(".white").removeClass("white");
            $(".white").addClass("blue");
            $(".crt_new_msg").hide();
            $(".msg_container").show();
            $.ajax({
                type: "POST",
                url: "/ajax/message",
                data: {id: id, action: "readMsg"},
                dataType: 'json',
                success: function(result) {

                    //  added by ervinne - prevent selection of multiple conversations
                    $(".active_vMsg").removeClass("active_vMsg");
                    //  ---
                    $("#msg_" + id).addClass("active_vMsg");
                    $("#senderName_" + id).addClass("white");


                    var getMessage = result[0].msg;
                    var getreplyMsg = result[0].replyMsg;

                    if (getreplyMsg[getreplyMsg.length - 1].authID != getreplyMsg[getreplyMsg.length - 1].senderID) {
                        $("#msgSeen_" + id).text("Seen: ");
                    }

                    //if (getMessage!=null && getreplyMsg==null) {
                    //    for (var a = 0; a<getMessage.length;a++) {
                    //	$(".messagesOne").html(viewMsgDesign(getMessage[a]));
                    //    }
                    //}

                    var recipientName = "";
                    if (getreplyMsg != null) {

                        //Reply Message
                        for (var a = 0; a < getreplyMsg.length; a++) {
                            // Message Design
                            ret += viewMsgDesign(getreplyMsg[a]);
                            var list_recipient = getreplyMsg[a].recipient_name;
                            var sendBy = getreplyMsg[a].sendBy;
                            // Additional
                            $(".deleteConversation").attr("data-id", getreplyMsg[0].conversationID);
                            $(".addPeopleConversation").attr("data-id", getreplyMsg[0].conversationID);
                            $(".addPeopleConversation").attr("data-re", getreplyMsg[a].recipient);
                            $(".addPeopleConversation").attr("data-name", getreplyMsg[a].recipient_name);
                        }

                        var recipient = getreplyMsg[0].recipient_name;
                        var recipient_length = getreplyMsg[0].recipient_name.length;
                        var recipient_json = {};
                        for (var a = 0; a < recipient_length; a++) {

                            if (getreplyMsg[0].authName != recipient[a].name) {
                                recipientName += recipient[a].name + ",";
                            }
                            recipient_json[recipient[a].userID] = recipient[a].name;
                        }
                        // Save json to dom
                        $("body").data(getreplyMsg[0].conversationID, recipient_json);

                        // Users in the conversation
                        var users = "";
                        var count_user = recipient_length - 1;
                        users += "<a class='dataTip imp cursor' data-original-title='";
                        $.each(recipient_json, function(id, val) {
                            if (getreplyMsg[0].authName != val) {
                                users += val;
                            }
                            users += "<br />";
                        });
                        users += "'>" + count_user + " other people</a>";

                        if (recipient_length == 0) {
                            var data = "<u title='" + getreplyMsg[0].title + "' class='title_" + getreplyMsg[0].msgID + "'>(" + getreplyMsg[0].title + ")</u> - " + sendBy;
                        } else if (recipient_length > 4) {
                            var data = "<u title='" + getreplyMsg[0].title + "'  class='title_" + getreplyMsg[0].msgID + "'>(" + getreplyMsg[0].title + ")</u> - Conversation Between You and " + users;
                        } else {
                            ///console.log(recipientName)
                            var recipient = recipientName.substring(0, recipientName.length - 1);
                            var data = "<u title='" + getreplyMsg[0].title + "'  class='title_" + getreplyMsg[0].msgID + "'>(" + getreplyMsg[0].title + ")</u> - Conversation Between " + recipient + " and You";
                        }

                    }

                    $(".messagesOne").html(ret);
                    $(".replyMsg_conversation").attr("data-id", id); // add id of selected msg on the msgbox
                    $(".replyMsg_conversation").focus();

                    $(".conversationTo").html(data);
                    $(".msgviewContent").hide();
                    limitText("u.title_" + getreplyMsg[0].msgID, 5);
                    $("#loading_" + id).hide();
                    $('.scrollbarP').perfectScrollbar({
                        wheelSpeed: 20,
                        wheelPropagation: false,
                        minScrollbarLength: 20
                    });
                    $('.scrollbarP').scrollTop($('.scrollbarP').prop("scrollHeight"));
                    $('.scrollbarP').perfectScrollbar('update');
                    $(".timeago").timeago();  // Time To go
                    $(".dataTip").tooltip({
                        html: true,
                        placement: "bottom"
                    });

                    // Color Box
                    for (var a = 0; a < getreplyMsg.length; a++) {
                        $(".group_1_" + getreplyMsg[a].msgID).colorbox({rel: 'group_1_' + getreplyMsg[a].msgID, width: "75%", height: "80%"});
                    }

                    //  ervinne: trigger event for opened message
                    $.event.trigger({
                        type: 'messageOpened',
                        messageData: {
                            id: id
                        }
                    });
                }
            });


        });
    },
    replyMsg_conversation: function() {
        //$(".replyMsg_conversation").autosize({append: "\n"});
        $("body").on("keypress", ".replyMsg_conversation", function(e) {
            if (e.keyCode == 13 && !e.shiftKey && !message.currentlySendingMessage) {
                message.currentlySendingMessage = true;
                e.preventDefault();
                var ret = "";
                var id = $(this).attr("data-id");
                var msg = $(".replyMsg_conversation").val();
                var msg = msg_nl2br(msg.replace(/\n/g, '<br>'));
                // File attachment
                var file_name = $(this).attr("data-file");
                var files = $(this).attr("data-get-file");
                var folder_location = $(this).attr("data-location");
                var imageLength = $("." + files).length;
                var img = {};
                $("." + files).each(function(eqindex) {
                    img['name_' + eqindex] = $(this).attr("data-name");
                });
                var addPeopleConversation = $(".addPeopleConversation").attr("data-re");
                if (id != "" && msg != "" || id != "" && imageLength != 0) {
                    var json_encode = JSON.stringify(img);

                    console.log({id: id, msg: msg, action: "replyMsg", imagesGet: json_encode, folder_location: folder_location, addPeopleConversation: addPeopleConversation});

                    $.post("/ajax/message", {id: id, msg: msg, action: "replyMsg", imagesGet: json_encode, folder_location: folder_location, addPeopleConversation: addPeopleConversation}, function(data) {
                        var countReply = $(".messagesOne > li").length;
                        var getMessage = jQuery.parseJSON(data);
                        //console.log(getMessage)
                        if (countReply != 0) {
                            $(viewMsgDesign(getMessage)).insertAfter(".messagesOne li:nth-child(" + countReply + ")");
                        } else {
                            $(".messagesOne").html(viewMsgDesign(getMessage));
                        }
                        $(".replyMsg_conversation").val(null);


                        $('.scrollbarP').perfectScrollbar({
                            wheelSpeed: 20
                        });

                        $('.scrollbarP').scrollTop($('.scrollbarP').prop("scrollHeight"));
                        $('.scrollbarP').perfectScrollbar('update');
                        //$("#msgContent_" + getMessage.conversationID).attr("title",msg_nl2br_2(getMessage.message))
                        //$("#msgContent_" + getMessage.conversationID).html(msg_nl2br_2(getMessage.message))
                        //$("#timeago_" + getMessage.conversationID).attr("title",getMessage.date);
                        //$(".timeago").timeago();  // Time To go
                        //limitText(".msgContent",20); // Limit title text on msg
                        //$("#msg_" + getMessage.conversationID).hide();
                        //$("#msgSeen_" + getMessage.conversationID).html(null);                        

                        var selectedConversationDivId = $('.active_vMsg').attr('id');

                        $(".loadMsgList").html(null);
                        $(".more").remove();
                        $(".load_m").show();
                        setTimeout(function() {
                            get_loadMsg("load", "loadMsg", "", "", function() {
                                //  reassign the selected conversation
                                if (typeof selectedConversationDivId !== 'undefined') {
                                    $('#' + selectedConversationDivId).addClass('active_vMsg');
                                }
                            });
                        });

                        // Remove images uploaded on the preview
                        $(".previewImagePostUpload").html(null);
                        $(".imagePreviewUpload").hide();
                        // Color Box
                        $(".group_1_" + getMessage.msgID).colorbox({rel: 'group_1_' + getMessage.msgID, width: "75%", height: "80%"});

                        $.event.trigger({
                            type: 'replyMessageSent',
                            messageData: {
                                id: id,
                                msg: msg,
                                message: msg, //  added for chat
                                action: 'replyMsg',
                                imagesGet: json_encode,
                                folder_location: folder_location,
                                addPeopleConversation: addPeopleConversation
                            }
                        });                        
                    });


                }
                $(".replyMsg_conversation").val(null);
                message.currentlySendingMessage = false;
            }
        });

        // Click
        //$("body").on("click",".replyMsg_conversation",function(){})
    },
    load_more_msg: function() {
        // Load More on Scrollbar
        $(".scrollbarM").bind('scroll', function() {
            if ($(".scrollbarM").scrollTop() + $(this).innerHeight() >= $(".scrollbarM")[0].scrollHeight) {

                var selectedConversationDivId = $('.active_vMsg').attr('id');
                var last_msgID = $(".more").attr("data-id");
                var last_modified = $(".more").attr("data-date");
                var action = "loadMsg";
                var type = "load_more";
                //$("#more_"+last_msgID).remove();

                //    $("#more_"+last_msgID).remove();

                $("#moreLbl_" + last_msgID).hide();
                $("#moreload_" + last_msgID).show();
                get_loadMsg(type, action, last_msgID, last_modified, function() {
                    //  reassign the selected conversation
                    if (typeof selectedConversationDivId !== 'undefined') {
                        $('#' + selectedConversationDivId).addClass('active_vMsg');
                    }
                });

            }
        });
    }
}